package com.xy.novelweb.service.readers;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xy.novelweb.dao.NovelMapper;
import com.xy.novelweb.dao.ReaderMapper;
import com.xy.novelweb.domain.*;
import com.xy.novelweb.utils.JedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Service
@Slf4j
public class ReaderServiceImp implements ReaderService {
		@Autowired
		private ReaderMapper readerMapper;
		@Autowired
		private NovelMapper novelMapper;

		@Override
		public Reader getReaderByName(String nickName) {
				//查看redis数据库是否存在改用户的信息
				//若存在则返回改用户，否则从数据库查询并保存到redis
//				Jedis jedis = JedisUtil.getConnect();
//				String key = "reader:" + nickName;
//				Reader reader = null;
//				try {
//						if (jedis.exists(key)) {
//								String value = jedis.get(key);
//								reader = new ObjectMapper().readValue(value, Reader.class);
//						} else {
//								reader = readerMapper.selectByPrimaryKey(nickName);
//								reader.setBirth(new SimpleDateFormat("yyyy-MM-dd").format(reader.getBirthday()));
//
//								String json = new ObjectMapper().writeValueAsString(reader);
//								jedis.setex(key, 60 , json);
//
//						}
//				} catch (Exception e) {
//						log.error("错误消息：{}", e.getMessage(), e);
//				} finally {
//						JedisUtil.close(jedis);
//				}
				Reader reader = readerMapper.getAllMsg(nickName);
				log.info("getReaderMsg reader=" + reader);
				return reader;
		}

		@Transactional
		@Override
		public int SetUserHeadImg(String nickName, String imgname) {
				int i = 0;
				String keu = "reader:" + nickName;
				if ("".equals(nickName) || "".equals(imgname) || nickName == null || imgname == null) {
						i = -1;
				} else {
						i = readerMapper.SetUserHeadImg(imgname, nickName);
						Jedis jedis = JedisUtil.getConnect();
						String value = jedis.get(keu);
						try {
								Reader reader = new ObjectMapper().readValue(value, Reader.class);
								reader.setHeadImage(imgname);
								int time = Math.toIntExact(jedis.ttl(keu));
								if (time == -1) {
										time = 60 * 60;
								}
								jedis.setex(keu, time, new ObjectMapper().writeValueAsString(reader));
						} catch (IOException e) {
								log.error("错误消息：{}", e.getMessage(), e);
						} finally {
								JedisUtil.close(jedis);
						}
				}

				return i;
		}

		@Transactional
		@Override
		public int UpdateReaderMsg(Reader reader) {
				Jedis jedis = JedisUtil.getConnect();
				String key = "reader:" + reader.getNickName();
				int flag = 0;
				try {
						//更新读者信息
						flag = readerMapper.updataReaderByName(reader);
						//如果数据库更新成功则更新redis
						if (flag == 1) {
								int time = Math.toIntExact(jedis.ttl(key)) == -2 ? 60 * 60 : Math.toIntExact(jedis.ttl(key));
								String value = "";
								Reader result = null;
								if (jedis.exists(key)) {
										value = jedis.get(key);
										result = new ObjectMapper().readValue(value, Reader.class);
										//修改变更字段
										result.setNickName(reader.getNickName());
										result.setSex(reader.getSex());
										result.setBirthday(reader.getBirthday());
										result.setAddress(reader.getAddress());
										result.setIntro(reader.getIntro());
								} else {
										result = readerMapper.selectByPrimaryKey(reader.getNickName());
								}
								time = time == -1 ? 60 * 60 : time;
								jedis.setex(key, time, new ObjectMapper().writeValueAsString(result));
								return 1;
						}
				} catch (IOException e) {
						log.error("错误消息：{}", e.getMessage(), e);
				} finally {
						JedisUtil.close(jedis);
				}
				return 0;
		}

		@Override
		public Reader findBookShelfByName(String nickName) {
				Reader reader = null;
				Jedis jedis = JedisUtil.getConnect();
				String key = "reader:" + nickName;

				try {
						if (jedis.exists(key)) {
								String value = jedis.get(key);
								reader = new ObjectMapper().readValue(value, Reader.class);
								if (reader.getMyBookShelf() == null) {
										reader.setMyBookShelf(readerMapper.findBookShelfByName(nickName));
										//获取key的过期时间，已过期设置为3600秒，
										int time = Math.toIntExact(jedis.ttl(key)) == -2 ? 60 * 60 : Math.toIntExact(jedis.ttl(key));
										jedis.setex(key, time, new ObjectMapper().writeValueAsString(reader));
								}
						} else {
								reader = readerMapper.getAllMsg(nickName);//readerMapper.findBookShelfByName(nickName);
								//更新redis的值
								if (reader != null) {
										//获取key的过期时间，已过期设置为3600秒，
										int time = Math.toIntExact(jedis.ttl(key)) == -2 ? 60 * 60 : Math.toIntExact(jedis.ttl(key));
										jedis.setex(key, time, new ObjectMapper().writeValueAsString(reader));
								}
						}

				} catch (Exception e) {
						log.error("错误消息：{}", e.getMessage(), e);
				} finally {
						JedisUtil.close(jedis);
				}
				return reader;
		}

		@Override
		public PageInfo<NovelShelf> getBookSelf(String nickName, int currentPage, int pageSize) {
				PageHelper.startPage(currentPage, pageSize);
				List<NovelShelf> shelf = readerMapper.findBookShelfByName(nickName);
				log.info("getBookSelf shelf=" + shelf);
				log.info("getBookSelf shelf=" + shelf);
				PageInfo<NovelShelf> info = new PageInfo<>(shelf);
				log.info("getBookSelf pageInfo=" + info);
				return info;
		}

		@Transactional
		@Override
		public int deletBookFromShelf(String nickName, int id) {
				Jedis jedis = JedisUtil.getConnect();
				String key = "reader:" + nickName;

				int result = 0;
				try {
						result = readerMapper.deletBookShelfById(id);
						if (result == 1) {
								String value = jedis.get(key);
								Reader reader = new ObjectMapper().readValue(value, Reader.class);
								List<NovelShelf> MyBookShelf = reader.getMyBookShelf();
								Iterator<NovelShelf> iterator = MyBookShelf.iterator();
								while (iterator.hasNext()) {
										NovelShelf n = iterator.next();
										if (id == n.getId()) {
												iterator.remove();
										}
								}

								reader.setMyBookShelf(MyBookShelf);
								jedis.set(key, new ObjectMapper().writeValueAsString(reader));
						}
				} catch (Exception e) {
						log.error("错误消息：{}", e.getMessage(), e);
				} finally {
						JedisUtil.close(jedis);
				}
				return result;
		}

		@Transactional
		@Override
		public boolean addBookMark(String nickName, String bookName, String catlogname) {
				Jedis jedis = JedisUtil.getConnect();
				String key = "reader:" + nickName;
				Reader reader = null;
				int flag = 0;
				boolean result = false;
				try {
						if (jedis.exists(key)) {
								String value = jedis.get(key);
								reader = new ObjectMapper().readValue(value, Reader.class);
								log.info("[reader:addmark]=" + reader);
								List<NovelShelf> MyBookShelf = reader.getMyBookShelf() == null ? readerMapper.findBookShelfByName(nickName) : reader.getMyBookShelf();

								Msg msg = checkBookShelf(MyBookShelf, nickName, bookName, catlogname);
								flag = (int) msg.getData();
								result = msg.isFlag();
								//如果没有找到，想数据库插入新的记录
								if (flag != 1) {
										result = readerMapper.addBookMark(nickName, bookName, catlogname);
										reader = readerMapper.getAllMsg(nickName);
								} else {
										reader.setMyBookShelf(MyBookShelf);
								}
								jedis.set(key, new ObjectMapper().writeValueAsString(reader));
						} else {

								reader = readerMapper.getAllMsg(nickName);
								List<NovelShelf> MyBookShelf = reader.getMyBookShelf();
								for (NovelShelf n : MyBookShelf) {
										if (catlogname.equals(n.getBookMark())) {
												flag = -1;
										}
								}
								if (flag != -1) {
										result = readerMapper.addBookMark(nickName, bookName, catlogname);
								}
								jedis.setex(key, 60 * 60, new ObjectMapper().writeValueAsString(reader));
						}
				} catch (Exception e) {
						log.error("错误消息：{}", e.getMessage(), e);
				} finally {
						JedisUtil.close(jedis);
				}
				return result;
		}

		@Override
		@Transactional
		public int buyOneCatalog(String novelName, String catalogName, Reader reader) {
				//1、获取参数和用户vip等级，根据vip等级计算用户需要支付的货币 （pay = 15*购买章节数 - vip等级；）
				if (reader.getVip() == null) {
						reader = readerMapper.getAllMsg(reader.getNickName());
				}
				int price = 15 - reader.getVip();
				//2、查询用户余额
				//3、用户余额小于价格则支付失败 返回-》余额不足请充值
				if (reader.getAccountBalance() < price) {
						return 100;
				}
				int result = -1;
				try {
						//4、支付成功 更新-》更新用户以购买章节，更新用户余额，更新订单
						String createTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date());
						readerMapper.addBuyRecord(reader.getNickName(), novelName, catalogName, createTime);
						float balance = readerMapper.getReaderBalance(reader.getNickName()) - price;
						boolean b = readerMapper.updateBalance(reader.getNickName(), balance);
						log.info("购买：" + b);
						readerMapper.addOrder(reader.getNickName(), price, createTime, "单章购买", "购买《" + novelName + "》的章节：" + catalogName);
						//5、返回购买成功
						result = 200;
						//6、刷新页面
				} catch (Exception e) {
						log.error("错误消息：{}", e.getMessage(), e);
						result = 400;//购买失败
				}
				return result;
		}

		@Override
		public Float getBalanceByName(String nickName) {
				return readerMapper.getReaderBalance(nickName);
		}

		/*
		 * 购买整本小说的vip章节
		 * */
		@Override
		public int buyCatalogs(Reader reader, String novelName) {
				//1、获取参数和用户vip等级，根据vip等级计算用户需要支付的货币（pay = (15- vip等级)*购买章节数 ；）
				String nickName = reader.getNickName();
				if (reader.getVip() == null) {
						reader = readerMapper.getAllMsg(reader.getNickName());
				}
				int needPayCatalogs = novelMapper.getUnBuyCatalogNum(novelName, nickName);
				int price = (15 - reader.getVip()) * needPayCatalogs;
				//2、查询用户余额
				float balance = readerMapper.getReaderBalance(nickName);
				//3、用户余额小于价格则支付失败 返回-》余额不足请充值
				if (balance < price) {
						return 100;
				}
				int result = -1;
				try {
						//4、支付成功 更新-》更新用户以购买章节，更新用户余额，更新订单
						String createTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date());
						//readerMapper.addBuyRecord(reader.getNickName(), novelName, catalogName, createTime);
						float pay = balance - price;

						readerMapper.addBuyRecords(nickName, novelName, createTime);

						readerMapper.addOrder(reader.getNickName(), price, createTime, "整本购买", "购买《" + novelName + "》的所有vip章节：");

						boolean b = readerMapper.updateBalance(reader.getNickName(), pay);

						//5、返回购买成功
						result = 200;
				} catch (Exception e) {
						log.error("错误消息：{}", e.getMessage(), e);
						result = 400;//购买失败
				}
				return result;
		}

		@Override
		@Transactional
		public void recharge(Reader reader, float totalAmount, String time, String remark) {
				try {
						String nickName = reader.getNickName();
						boolean flag = readerMapper.addRechargeRecord(nickName, totalAmount, time, remark);
						if (flag) {
								float balance = readerMapper.getReaderBalance(nickName);
								readerMapper.updateBalance(nickName, balance + totalAmount*10);
								int leave=10^(reader.getVip()+1);
								log.info(("userLeave="+leave));
								int amt = ((int) (balance + totalAmount*10)/10);
								if(amt>leave&&reader.getVip()<10){
										readerMapper.updateVipLeave(reader.getNickName());
								}
						}
				} catch (Exception e) {
						log.error("错误消息：{}", e.getMessage(), e);
				}
		}

		@Override
		public PageInfo<ReaderRechargeRecord> getRechargeList(String nickName, int currentPage, int pageSize) {
				List<ReaderRechargeRecord> records = null;
				PageInfo<ReaderRechargeRecord> pi = null;
				try {
						PageHelper.startPage(currentPage, pageSize);
						records = readerMapper.selectRechargeByName(nickName);
						pi = new PageInfo<>(records);
						log.info("readerService recharge pageInfo=" + pi);
				} catch (Exception e) {
						log.error("错误消息：{}", e.getMessage(), e);
				}
				return new PageInfo<>(records);
		}

		@Override
		public PageInfo<ConsumptionRecord> getConsumptionList(String nickName, int currentPage, int pageSize) {
				List<ConsumptionRecord> records = null;
				PageInfo<ConsumptionRecord> pi = null;
				try {
						PageHelper.startPage(currentPage, pageSize);
						records = readerMapper.selectConsumptionByName(nickName);
						pi = new PageInfo<>(records);
						log.info("readerService consumption pageInfo=" + pi);
				} catch (Exception e) {
						log.error("错误消息：{}", e.getMessage(), e);
				}
				return pi;
		}

		@Override
		public PageInfo<Comment> getComments(String nickName, int currentPage, int pageSize) {
				PageHelper.startPage(currentPage, pageSize);
				List<Comment> list = readerMapper.selectReaderComments(nickName);
				log.info("ReaderService getComments list:" + list.size());
				return new PageInfo<>(list);
		}

		@Override
		@Transactional
		public int addComment(String novelName, String catalog, String readerName, String context, String url) {
				int result = -1;
				try {
						Comment comment = new Comment();
						comment.setCommentUrl(url);//设置评论url
						Reader reader = new Reader();
						reader.setNickName(readerName);
						comment.setCommentAuthor(reader);//设置评论人
						comment.setCommentContext(context);//设置评论内容
						comment.setCommentTitle(catalog);//设置小说章节名
						comment.setCommentTime(new Date());//设置评论日期

						int id = readerMapper.addUserComment(comment);
						if (id==1){

								result = readerMapper.addNovelComment(comment.getId(), novelName) ? 200 : -200;

								result = readerMapper.addReaderComment(readerName, catalog, comment.getId()) ? 200 : -200;
						}

				} catch (Exception e) {
						log.error("错误消息：{}", e.getMessage(), e);
				}
				return result;
		}

		@Override
		public boolean checkPassword(String nickName, String oldPassword) {
				int count = readerMapper.selectReaderByPwd(nickName,oldPassword);
				return count==1;
		}

		@Transactional
		@Override
		public void updatePassword(String oldPassword, String newPassword, String nickName) {
				readerMapper.updatePassword(nickName,oldPassword,newPassword);
		}

		public Msg checkBookShelf(List<NovelShelf> MyBookShelf, String nickName, String bookName, String catlogname) {
				Msg msg = new Msg(false);
				msg.setData(0);
				boolean result = false;
				Iterator<NovelShelf> iterator = MyBookShelf.iterator();
				while (iterator.hasNext()) {
						NovelShelf n = iterator.next();
						//如果书架有小说，就更新书签
						if (bookName.equals(n.getNovelName().getBookName())) {
								msg.setData(1);
						}
						if (bookName.equals(n.getNovelName().getBookName()) && !catlogname.equals(n.getBookMark())) {
								//如果书架有小说，就更新书签
								//同时更新数据库
								n.setBookMark(catlogname);
								result = readerMapper.updateBookMark(nickName, bookName, catlogname);
								msg.setFlag(result);
						}
				}
				return msg;
		}

}
